package org.yunai.swjg.server.core.service;

import org.yunai.yfserver.server.NamedThreadFactory;
import org.yunai.yfserver.util.ExecutorUtils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 系统线程池服务器
 * User: yunai
 * Date: 13-4-27
 * Time: 下午2:34
 */
public class GameExecutorService {

    /**
     * 处理进程相关的线程池
     */
    private final ScheduledExecutorService processExecutorService;
    /**
     * 执行定时任务的线程池
     */
    private final ScheduledExecutorService scheduledExecutorService;

    public GameExecutorService() {
        this.processExecutorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(getClass(), "processExecutorService"));
        this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(getClass(), "scheduledExecutorService"));
    }

    /**
     * [processExecutorService]添加按指定的周期执行任务
     *
     * @param task   任务
     * @param period 执行周期，单位(毫秒)
     */
    public void processTask(Runnable task, long period) {
        scheduledExecutorService.scheduleAtFixedRate(task, 0, period, TimeUnit.MILLISECONDS);
    }

    /**
     * [scheduledExecutorService]添加按指定的周期执行任务
     *
     * @param task   任务
     * @param period 执行周期，单位(毫秒)
     */
    public void scheduleTask(Runnable task, long period) {
        scheduledExecutorService.scheduleAtFixedRate(task, 0, period, TimeUnit.MILLISECONDS);
    }

    public void stop() {
        ExecutorUtils.shutdownAndAwaitTermination(processExecutorService);
        ExecutorUtils.shutdownAndAwaitTermination(scheduledExecutorService);
    }
}
